<?php
/**
 * @copyright ©2018 Lu Wei
 * @author Lu Wei
 * @link http://www.luweiss.com/
 *
 * Created by IntelliJ IDEA.
 * Date Time: 2018/4/13 17:53
 */


namespace luweiss\wechat;


use Doctrine\Common\Cache\FilesystemCache;

class Cache
{
    public $cacheDriver;


    /**
     * Cache constructor.
     * @param array $args
     *
     * [
     *
     * 'type'=>'file|memcache|memcached|redis',
     *
     * 'cacheDir'=>'file cache save dir',
     *
     * 'memcacheHost'=>'memcacheHost',
     *
     * 'memcachePort'=>'memcachePort',
     *
     * ]
     */
    public function __construct($args = [])
    {
        $args['type'] = isset($args['type']) ? $args['type'] : 'file';
        if ($args['type'] == 'file') {
            $args['cacheDir'] = isset($args['cacheDir']) ? $args['cacheDir'] : __DIR__ . '/../runtime/cache';
            $this->cacheDriver = new FilesystemCache($args['cacheDir']);
        } elseif ($args['type'] == 'memcache') {
        }
    }

    /**
     * Fetches a value from the cache.
     *
     * @param string $key The unique key of this item in the cache.
     * @param mixed $default Default value to return if the key does not exist.
     *
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
     *
     */
    public function get($key, $default = null)
    {
        $res = $this->cacheDriver->fetch($key);
        if ($res === false)
            return $default;
        return $res;
    }

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * @param string $key The key of the item to store.
     * @param mixed $value The value of the item to store, must be serializable.
     * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     */
    public function set($key, $value, $ttl = null)
    {
        return $this->cacheDriver->save($key, $value, $ttl);
    }

    /**
     * Delete an item from the cache by its unique key.
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     */
    public function delete($key)
    {
        return $this->cacheDriver->delete($key);
    }

    /**
     * Wipes clean the entire cache's keys.
     *
     * @return bool True on success and false on failure.
     */
    public function clear()
    {
        return $this->cacheDriver->deleteAll();
    }
}